import { Table, Space, ImgDefault, Icon, message, Tooltip, Button, Drawer, Modal, Switch, Empty } from '@bytedance/mona-ui';
import React, { useState, useCallback, useEffect, useImperativeHandle, forwardRef, useRef } from 'react';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import { getRepeatProdectList } from '@Api/producToptimize/RepeatProdect'
import EditProdect from './editProdect'
import EditProgress from './editProgress'
import { format } from './postDataInfo'
import { store, useAppSelector } from "~store"

function RepeatProdect(props: any, ref: any) {
    interface ITableData {
        base_item_info: any;
        extra_item_info: any;
        statistics_info: any;
        threshold_info: any;
    }


    const [lodinDatSttuas, setLodinDatSttuas] = useState<boolean>(false)
    const [optimizationList, setOptimizationList] = useState<ITableData[]>([])
    const [openEditBox, setOpenEditBox] = useState<boolean>(false)
    const [editList, setEditList] = useState<any>([])
    // console.log('optimizationList', optimizationList)
    const columnsList: ColumnProps<ITableData>[] = [
        {
            title: '商品信息',
            key: '0',
            width: 350,
            render: (text: any, record: any) => {
                return (
                    <Space>
                        <ImgDefault src={record.base_item_info?.pic_url} alt="" style={{ width: '50px', height: '50px' }} />
                        <Space direction="vertical">
                            <div className="name" style={{
                                width: 200,
                            }}>
                                {record.base_item_info?.item_name}
                            </div>
                            <div className="idcone" style={{
                                color: "#85878a"
                            }}>
                                <span className="id">ID：{record.base_item_info?.item_id}</span>
                                <Icon type="CopyIcon" className="copyiconitem"
                                    style={{
                                        marginLeft: 5,
                                        cursor: "pointer"
                                    }}
                                    onClick={() => copyToClipboard(record.base_item_info?.item_id)}> </Icon>
                            </div>
                        </Space>
                    </Space>
                )
            }
        },
        {
            title: '商品表现',
            key: '1',
            align: 'left',
            width: 180,
            render: (text: any, record: any) => {
                return (
                    <Space direction="vertical" size={1.5}>
                        <Space>
                            <span className="title">综合好评
                                <Tooltip title="综合好评=(商品好评数+店铺好评率*50) / (商品评价数+50)">
                                    <Icon type='DoubtIcon'></Icon>

                                </Tooltip>
                            </span>
                            <span className="title">{(record.extra_item_info?.good_comment_ratio * 100)?.toFixed(2)}%</span>
                        </Space>
                        <Space>
                            <span className="title">综合差评
                                <Tooltip title="综合差评=(商品差评数+店铺差评率*50) / (商品评价数+50)">
                                    <Icon type='DoubtIcon'></Icon>

                                </Tooltip>
                            </span>
                            <span className="title">{(record.extra_item_info?.bad_comment_ratio * 100)?.toFixed(2)}%</span>
                        </Space>
                        <Space>
                            <span className="title">历史销量 </span>
                            <span className="title">{record.extra_item_info?.sell_num}</span>
                        </Space>
                        <Space>
                            <span className="title">商品品质力分层 </span>
                            <span className="title">{record.extra_item_info?.item_level}</span>
                        </Space>
                    </Space>

                )
            }
        },
        {
            title: '近30日商城数据',
            key: '2',
            align: 'left',
            width: 180,
            render: (text: any, record: any) => {
                return (
                    <Space direction="vertical" size={1.5}>
                        <Space>
                            <span className="title">成交金额
                                <Tooltip title="用户通过商城范围内的入口进入直播间、观看短视频或直接点击商品卡片后成交的订单金额，包含用户先将商品加入购物车后在购物车支付的订单金额，不去除退款退货的订单金额">
                                    <Icon type='DoubtIcon'></Icon>

                                </Tooltip>
                            </span>
                            <span className="title">{(record.statistics_info?.gmv_num / 100)?.toFixed(2)}</span>
                        </Space>
                        <Space>
                            <span className="title">成交订单数
                                <Tooltip title="用户通过商城范围内的入口进入直播间、观看短视频或直接点击商品卡片后成交的订单数量，包含用户先将商品加入购物车后在购物车支付的订单数量，不去除退款退货的订单数量">
                                    <Icon type='DoubtIcon'></Icon>

                                </Tooltip>
                            </span>
                            <span className="title">{record.statistics_info?.sale_num} </span>
                        </Space>
                        <Space>
                            <span className="title">点击人数
                                <Tooltip title="包含通过商城范围内的入口进入直播间后点击商品的行为、在短视频上点击购物车或者商品的行为、直接点击页面上展示的商品卡卡片的行为，以上三种行为的去重人数 去重逻辑：用户在筛选时间内多次点击商品计算为一个人；用户在直播间、观看短视频、商品卡都点击过商品，计算为一个人">
                                    <Icon type='DoubtIcon'></Icon>
                                </Tooltip>
                            </span>
                            <span className="title">{record.statistics_info?.exposure_num}</span>
                        </Space>

                    </Space>

                )
            }
        },
        {
            title: '入池诊断及优化建议',
            key: '3',
            align: 'left',
            render: (text: any, record: any) => {
                const renderList = record.threshold_info.filter(item => item.threshold_status === 2)
                return <Space direction="vertical">
                    {renderList.map(item => {
                        return <Space direction="vertical" key={item.threshold_id}>
                            <Space>
                                <Icon type='ErrorIcon' style={{
                                    color: '#FF4D4F',
                                }}></Icon>
                                <span className="title">{item.threshold_name}</span>
                            </Space>
                            <Space>
                                <div className="content">
                                    {item.threshold_desc}
                                </div>
                                {item.tips_list && item.tips_list.length && <Tooltip title={item.tips_list && item.tips_list.length ? item.tips_list.join('；') : '暂无优化建议'}>
                                    <Icon type='DoubtIcon'></Icon>
                                </Tooltip>}
                            </Space>

                        </Space>
                    })}
                    <Button type='link' onClick={() => {
                        if (!cheackLoginfatyer()) return
                        // setEditList([{
                        //     id: '3693637386132128242'
                        // }, {
                        //     id: '3701320919373971611'
                        // }, {
                        //     id: '3697378867443531850'
                        // }])
                        setEditList([{
                            id: record.base_item_info?.item_id, //'3706290759142604966',// record.base_item_info?.item_id,
                            record
                        },
                            // {
                            //     id: '3677478310465634577',// record.base_item_info?.item_id,
                            //     record
                            // }, {
                            //     id: '3703686402685403149',// record.base_item_info?.item_id,
                            //     record
                            // }, {
                            //     id: '3689783643032649913',// record.base_item_info?.item_id,
                            //     record
                            // }, {
                            //     id: '3678052012894847357',// record.base_item_info?.item_id,
                            //     record
                            // }, {
                            //     id: '3707031853845315834',// record.base_item_info?.item_id,
                            //     record
                            // }

                        ])

                        setOpenEditBox(true)
                        // setOpenBatchEdit(true)
                    }}>立即优化重复铺货</Button>
                </Space>


            }
        }
    ];
    // const addnewPrd: any = useAppSelector((state) => state.autoCounps.addnewPrd)
    const isBuyStatus = useAppSelector((state) => state.jinritemaiProduct.isBuyStatus)
    function cheackLoginfatyer(show = false) {
        // console.log('addnewPrd', addnewPrd)
        // if (!addnewPrd) {
        //     if (!show) {
        //         Modal.warning({
        //             title: "提示",
        //             content: (
        //                 <>
        //                     插件版本过旧无法使用请前往官网
        //                     <Button
        //                         type="link"
        //                         onClick={(e) => {
        //                             open("https://doulingyang.cn")
        //                         }}>
        //                         doulingyang.cn
        //                     </Button>
        //                     下载最新版本后刷新页面使用！！
        //                 </>
        //             ),
        //             okText: "知道了",
        //             centered: false
        //         })
        //         return false
        //     }
        //     return false
        // }
        // console.log('isBuyStatus.status', isBuyStatus)
        if (isBuyStatus.status) {
            if (!show) {
                Modal.confirm({
                    title: isBuyStatus.title,
                    content: isBuyStatus.content,
                    icon: null,
                    okText: isBuyStatus.okText,
                    cancelText: " 取消",
                    onOk: () => {
                        open(isBuyStatus.url)
                        return
                    }
                })
                return false
            }

            return false
        }
        // console.log('cheackLogin()', cheackLogin())
        // if (cheackLogin()) {
        //     if (!show) {
        //         Modal.warning({
        //             title: "提示",
        //             content: "请先登录后使用插件",
        //             okText: "前往登录",
        //             onOk: () => {
        //                 setShowLoginBox(true)
        //             }
        //             // centered: false,
        //         })
        //         return false
        //     }
        //     return false
        // }
        return true
    }
    async function init() {
        setLodinDatSttuas(true)
        const getListQuery = {
            "have_sell": true, // true 有动销待优化   false 无动销待优化
            "in_pool": false,
            "item_info": "",
            "page": {
                "current": 1,
                "page_size": 500 // 500 ***
            },
            "un_reached_threshold_list": [6]
        }
        const dataArr: any = []

        async function initGetRepeatProdectList(query: any) {
            const getListData: any = await getRepeatProdectList(query).catch(err => {
                return false
            })
            if (getListData && getListData.code === 200) {
                // getListData.total ***
                if (getListData.total > query.page.page_size * query.page.current) {
                    query.page.current += 1
                    dataArr.push(...getListData.data)
                    return initGetRepeatProdectList(query)
                }
                if (query.have_sell) {
                    query.have_sell = false
                    query.page.current = 1
                    dataArr.push(...getListData.data)
                    return initGetRepeatProdectList(query)
                }
                dataArr.push(...getListData.data)
                return dataArr
            }
            return []
        }
        const listData = await initGetRepeatProdectList(getListQuery)
        // console.log('listData', listData)
        setLodinDatSttuas(false)
        setOptimizationList(listData.filter(geterritem => {
            const getChonfu = geterritem.threshold_info.find(item => {
                // 之前方案
                if (item.threshold_status === 2 && item.threshold_id === 6) { //  === 6 ***
                    return true
                }
                // if (item.threshold_id === 6) {
                //     return true
                // }
                return false
            })
            return getChonfu
        }).map((item, index) => {
            // console.log('item', item)
            item.index = index
            item.product_id = item.base_item_info.item_id
            return item
        }
        ))

    }
    const fetchData = useCallback(() => {
        init()
    }, []);
    useEffect(() => {
        fetchData();
    }, [fetchData]);
    function copyToClipboard(text) {
        navigator.clipboard
            .writeText(text)
            .then(function () {
                message.success("复制成功")
            })
            .catch(function (err) {
                message.error("复制失败")
            })
    }
    function someMethod() {
        console.log('确定提交数据')
    }
    useImperativeHandle(ref, () => ({
        someMethod,
    }));
    const editDataRef = useRef<any>(null)
    const [openBatchEdit, setOpenBatchEdit] = useState(false)
    const [upDataIntersData, setUpDataIntersData] = useState<any>(null)
    const [selectedRowKeys, setSelectedRowKeys] = useState<any>([])
    const rowSelection = {
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,],
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            setSelectedRowKeys(selectedRowKeys)
        },
    }
    const [showSelectList, setshowSelectList] = useState(false)
    const getListeFunc = () => {
        if (showSelectList) {
            return optimizationList.filter((item: any) => {
                return selectedRowKeys.includes(item.product_id)
            })
        }
        return optimizationList
    }
    return <>
        {/* <Button onClick={init}>123</Button> */}
        <Table
            rowSelection={rowSelection}
            loading={lodinDatSttuas}
            columns={columnsList}
            rowKey="product_id"
            dataSource={getListeFunc()}
            locale={{
                emptyText: <Empty className="empty-img-emotion" description="没有发现重复铺货商品" />
            }}
            scroll={{ y: 900 }}
            pagination={{
                total: getListeFunc().length,
                // pageSize: 20,
                showTotal: (total) => `共 ${total} 条数据`,

                // onChange: (page, pageSize) => {
                //     setOptimizationList(optimizationList.slice((page - 1) * pageSize, page * pageSize))
                // }
            }}
            title={() => {
                return <Space align="center" style={{
                    width: '100%',
                    justifyContent: 'flex-end'
                }}>
                    <Space align='center'>
                        显示已选商品<Switch size="small" checked={showSelectList} onChange={(e) => {
                            setshowSelectList(e)
                        }}></Switch>
                    </Space>
                    <span>已选{selectedRowKeys.length}个商品</span>
                    <Button size="mini" type="primary" onClick={() => {

                        if (!selectedRowKeys.length) {
                            return Modal.warning({
                                title: '提示',
                                content: '请选择商品',
                                // onOk() {
                                //     // console.log('OK');
                                // }
                            })

                        }


                        if (selectedRowKeys.length > 30) {
                            Modal.warning({
                                title: '提示',
                                content: '单次最多只能选择30个商品',
                                // onOk() {
                                //     // console.log('OK');
                                // }
                            })
                            return
                        }
                        if (!cheackLoginfatyer()) return
                        // console.log('selectedRowKeys', selectedRowKeys)
                        const setItemData = optimizationList.filter((item) => {
                            return selectedRowKeys.includes(item.base_item_info.item_id)
                        }).map((item) => {
                            return {
                                id: item.base_item_info.item_id,
                                record: item
                            }
                        })
                        // console.log('setItemData', setItemData)
                        setEditList(() => [...setItemData])
                        setOpenEditBox(true)
                    }}>批量编辑</Button>
                    <Button size='mini' type="primary" onClick={init} icon={<Icon type='RefreshIcon'></Icon>}>刷新列表</Button>
                </Space >


            }}
        >
        </Table >
        <Drawer
            destroyOnClose
            width={1100}
            visible={openEditBox}
            size="small"
            title="编辑商品"
            className='noster'
            onCancel={() => setOpenEditBox(false)}
            // isSubDrawer
            bodyStyle={{
                // padding: 0
                padding: '12px 24px 12px',
                boxSizing: 'border-box',
                position: 'relative',
                overflowY: 'scroll',
                overflowX: 'hidden'
            }}
            onOk={() => {
                // console.log('进入收集提交数据阶段', editDataRef)
                if (editDataRef.current) {
                    const getDatasAll = editDataRef.current.someMethod()
                    // console.log('getDatasAll', getDatasAll)
                    format(getDatasAll)
                    return
                }
                message.error('请先编辑商品')
            }}
            footer={<Space align="center" style={{
                width: '100%',
                justifyContent: 'flex-end'
            }}>
                <Button type="secondary" icon={<Icon type="AiDrawIcon"></Icon>} onClick={() => {
                    upDataIntersData.forEach(item => {
                        item.isAiEdit = true
                        item.upLodinStuas = 0
                        item.upStatusText = '数据处理中...'
                        item.upTypeText = 'cancel'
                    })
                    // setUpDataIntersData((prev: any) => [...upDataIntersData])
                    setOpenBatchEdit(true)
                }}>一键智能编辑</Button>
                <Button type="primary" onClick={() => {
                    // if (editDataRef.current) {
                    //     const getDatasAll = editDataRef.current.someMethod()
                    //     // console.log('getDatasAll', getDatasAll)
                    //     format(getDatasAll)
                    //     return
                    // }
                    console.log('upDataIntersData', upDataIntersData)
                    upDataIntersData.forEach(item => {
                        item.isAiEdit = false
                        item.upLodinStuas = 0
                        item.upStatusText = '数据处理中...'
                        item.upTypeText = 'cancel'
                    })
                    // setUpDataIntersData((prev: any) => [...upDataIntersData])
                    setOpenBatchEdit(true)
                    // message.error('请先编辑商品')
                }}>确定编辑</Button>
                <Button onClick={() => setOpenEditBox(false)}>取消</Button>
            </Space>}
        >
            <EditProdect editProdectId={editList} ref={editDataRef} onChangeUpData={(e) => {
                setUpDataIntersData((prev: any) => [...e])
            }}></EditProdect>
            <Drawer
                title="批量编辑进度"
                visible={openBatchEdit}
                width={1100}
                destroyOnClose
                onCancel={() => setOpenBatchEdit(false)}
                footer={null}
            // isSubDrawer
            >
                <EditProgress editProdectId={upDataIntersData} />

            </Drawer>
        </Drawer>



    </>
}
export default forwardRef(RepeatProdect)